/**
 * 数据导入工具
 */

/**
 * 解析CSV文件
 * @param {File} file - CSV文件
 * @returns {Promise<Array>} 解析后的数据数组
 */
export function parseCSV(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    
    reader.onload = (e) => {
      try {
        const text = e.target.result
        const lines = text.split('\n').filter(line => line.trim())
        
        if (lines.length === 0) {
          reject(new Error('文件为空'))
          return
        }
        
        // 解析表头
        const headers = lines[0].split(',').map(header => header.trim().replace(/"/g, ''))
        
        // 解析数据行
        const data = []
        for (let i = 1; i < lines.length; i++) {
          const values = parseCSVLine(lines[i])
          if (values.length === headers.length) {
            const row = {}
            headers.forEach((header, index) => {
              row[header] = values[index]
            })
            data.push(row)
          }
        }
        
        resolve({
          headers,
          data,
          totalRows: lines.length - 1
        })
      } catch (error) {
        reject(error)
      }
    }
    
    reader.onerror = () => {
      reject(new Error('文件读取失败'))
    }
    
    reader.readAsText(file, 'UTF-8')
  })
}

/**
 * 解析CSV行（处理引号和逗号）
 * @param {string} line - CSV行
 * @returns {Array} 解析后的值数组
 */
function parseCSVLine(line) {
  const values = []
  let current = ''
  let inQuotes = false
  
  for (let i = 0; i < line.length; i++) {
    const char = line[i]
    
    if (char === '"') {
      if (inQuotes && line[i + 1] === '"') {
        // 转义的引号
        current += '"'
        i++ // 跳过下一个引号
      } else {
        // 开始或结束引号
        inQuotes = !inQuotes
      }
    } else if (char === ',' && !inQuotes) {
      // 字段分隔符
      values.push(current.trim())
      current = ''
    } else {
      current += char
    }
  }
  
  // 添加最后一个字段
  values.push(current.trim())
  
  return values
}

/**
 * 解析JSON文件
 * @param {File} file - JSON文件
 * @returns {Promise<Array>} 解析后的数据数组
 */
export function parseJSON(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    
    reader.onload = (e) => {
      try {
        const text = e.target.result
        const data = JSON.parse(text)
        
        if (!Array.isArray(data)) {
          reject(new Error('JSON文件必须包含数组数据'))
          return
        }
        
        if (data.length === 0) {
          reject(new Error('文件为空'))
          return
        }
        
        // 获取表头
        const headers = Object.keys(data[0])
        
        resolve({
          headers,
          data,
          totalRows: data.length
        })
      } catch (error) {
        reject(error)
      }
    }
    
    reader.onerror = () => {
      reject(new Error('文件读取失败'))
    }
    
    reader.readAsText(file, 'UTF-8')
  })
}

/**
 * 解析Excel文件（需要xlsx库）
 * @param {File} file - Excel文件
 * @returns {Promise<Array>} 解析后的数据数组
 */
export function parseExcel(file) {
  return new Promise((resolve, reject) => {
    // 这里需要安装 xlsx 库: npm install xlsx
    // import * as XLSX from 'xlsx'
    
    reject(new Error('Excel解析功能需要安装xlsx库: npm install xlsx'))
    
    // 示例代码（需要xlsx库）:
    /*
    const reader = new FileReader()
    
    reader.onload = (e) => {
      try {
        const data = new Uint8Array(e.target.result)
        const workbook = XLSX.read(data, { type: 'array' })
        const sheetName = workbook.SheetNames[0]
        const worksheet = workbook.Sheets[sheetName]
        const jsonData = XLSX.utils.sheet_to_json(worksheet)
        
        if (jsonData.length === 0) {
          reject(new Error('文件为空'))
          return
        }
        
        const headers = Object.keys(jsonData[0])
        
        resolve({
          headers,
          data: jsonData,
          totalRows: jsonData.length
        })
      } catch (error) {
        reject(error)
      }
    }
    
    reader.onerror = () => {
      reject(new Error('文件读取失败'))
    }
    
    reader.readAsArrayBuffer(file)
    */
  })
}

/**
 * 验证导入数据
 * @param {Array} data - 要验证的数据
 * @param {Array} rules - 验证规则
 * @returns {Object} 验证结果
 */
export function validateImportData(data, rules) {
  const errors = []
  const warnings = []
  const validData = []
  
  data.forEach((row, index) => {
    const rowErrors = []
    const rowWarnings = []
    
    // 验证必填字段
    rules.forEach(rule => {
      if (rule.required && (!row[rule.field] || row[rule.field].toString().trim() === '')) {
        rowErrors.push(`${rule.label}不能为空`)
      }
      
      // 验证数据类型
      if (row[rule.field] && rule.type) {
        const value = row[rule.field]
        
        switch (rule.type) {
          case 'number':
            if (isNaN(Number(value))) {
              rowErrors.push(`${rule.label}必须是数字`)
            }
            break
          case 'email':
            const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
            if (!emailRegex.test(value)) {
              rowErrors.push(`${rule.label}格式不正确`)
            }
            break
          case 'phone':
            const phoneRegex = /^1[3-9]\d{9}$/
            if (!phoneRegex.test(value)) {
              rowWarnings.push(`${rule.label}格式可能不正确`)
            }
            break
          case 'date':
            if (isNaN(Date.parse(value))) {
              rowErrors.push(`${rule.label}日期格式不正确`)
            }
            break
        }
      }
      
      // 验证长度
      if (row[rule.field] && rule.maxLength && row[rule.field].length > rule.maxLength) {
        rowErrors.push(`${rule.label}长度不能超过${rule.maxLength}个字符`)
      }
      
      if (row[rule.field] && rule.minLength && row[rule.field].length < rule.minLength) {
        rowErrors.push(`${rule.label}长度不能少于${rule.minLength}个字符`)
      }
    })
    
    if (rowErrors.length > 0) {
      errors.push({
        row: index + 1,
        errors: rowErrors
      })
    } else {
      validData.push(row)
    }
    
    if (rowWarnings.length > 0) {
      warnings.push({
        row: index + 1,
        warnings: rowWarnings
      })
    }
  })
  
  return {
    valid: errors.length === 0,
    validData,
    errors,
    warnings,
    totalRows: data.length,
    validRows: validData.length,
    errorRows: errors.length
  }
}

/**
 * 数据转换
 * @param {Array} data - 原始数据
 * @param {Object} mapping - 字段映射
 * @returns {Array} 转换后的数据
 */
export function transformData(data, mapping) {
  return data.map(row => {
    const transformedRow = {}
    
    Object.keys(mapping).forEach(targetField => {
      const sourceField = mapping[targetField]
      if (sourceField && row[sourceField] !== undefined) {
        transformedRow[targetField] = row[sourceField]
      }
    })
    
    return transformedRow
  })
}

/**
 * 获取默认的导入规则
 * @param {string} type - 数据类型
 * @returns {Array} 验证规则
 */
export function getDefaultImportRules(type) {
  const rulesMap = {
    users: [
      { field: 'username', label: '用户名', required: true, maxLength: 50 },
      { field: 'name', label: '姓名', required: true, maxLength: 100 },
      { field: 'email', label: '邮箱', required: true, type: 'email' },
      { field: 'phone', label: '手机号', required: true, type: 'phone' },
      { field: 'department', label: '部门', maxLength: 100 },
      { field: 'role', label: '角色', maxLength: 50 }
    ],
    products: [
      { field: 'code', label: '商品编码', required: true, maxLength: 50 },
      { field: 'name', label: '商品名称', required: true, maxLength: 200 },
      { field: 'category', label: '分类', maxLength: 100 },
      { field: 'specification', label: '规格', maxLength: 200 },
      { field: 'unit', label: '单位', maxLength: 20 },
      { field: 'purchasePrice', label: '采购价', type: 'number' },
      { field: 'salePrice', label: '销售价', type: 'number' },
      { field: 'stock', label: '库存', type: 'number' }
    ],
    suppliers: [
      { field: 'code', label: '供应商编码', required: true, maxLength: 50 },
      { field: 'name', label: '供应商名称', required: true, maxLength: 200 },
      { field: 'contact', label: '联系人', required: true, maxLength: 100 },
      { field: 'phone', label: '联系电话', required: true, type: 'phone' },
      { field: 'email', label: '邮箱', type: 'email' },
      { field: 'address', label: '地址', maxLength: 500 },
      { field: 'category', label: '供应类别', maxLength: 100 }
    ],
    customers: [
      { field: 'code', label: '客户编码', required: true, maxLength: 50 },
      { field: 'name', label: '客户名称', required: true, maxLength: 200 },
      { field: 'type', label: '客户类型', maxLength: 50 },
      { field: 'contact', label: '联系人', required: true, maxLength: 100 },
      { field: 'phone', label: '联系电话', required: true, type: 'phone' },
      { field: 'email', label: '邮箱', type: 'email' },
      { field: 'address', label: '地址', maxLength: 500 },
      { field: 'creditLimit', label: '信用额度', type: 'number' }
    ]
  }
  
  return rulesMap[type] || []
}

/**
 * 获取默认的字段映射
 * @param {string} type - 数据类型
 * @returns {Object} 字段映射
 */
export function getDefaultFieldMapping(type) {
  const mappingMap = {
    users: {
      username: '用户名',
      name: '姓名',
      email: '邮箱',
      phone: '手机号',
      department: '部门',
      role: '角色'
    },
    products: {
      code: '商品编码',
      name: '商品名称',
      category: '分类',
      specification: '规格',
      unit: '单位',
      purchasePrice: '采购价',
      salePrice: '销售价',
      stock: '库存'
    },
    suppliers: {
      code: '供应商编码',
      name: '供应商名称',
      contact: '联系人',
      phone: '联系电话',
      email: '邮箱',
      address: '地址',
      category: '供应类别'
    },
    customers: {
      code: '客户编码',
      name: '客户名称',
      type: '客户类型',
      contact: '联系人',
      phone: '联系电话',
      email: '邮箱',
      address: '地址',
      creditLimit: '信用额度'
    }
  }
  
  return mappingMap[type] || {}
}
